package com.elite.groovy.callback

import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.kh.KHUtil
import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.Util
import com.wisdge.dataservice.Result
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: 同步接口数据
 *
 */

public class apiSyncAPIData implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiSyncAPIData.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        long startTime = System.currentTimeMillis();

        String getMethod = request.getMethod();
        log.debug("apiSyncDBData getMethod:" + getMethod);
        String outData = "";
        if (getMethod != "GET") {
            outData = "HTTP请求调用类型错误，接口调用失败：" + getMethod;
            log.error(outData);
            return JSONObject.toJSONString(new Result(Result.ERROR, outData));
        }

        //获取所有参数名
        Enumeration ep = request.getParameterNames();
        while (ep.hasMoreElements()) {
            String parameterName = (String) ep.nextElement();
            log.debug(parameterName + ": " + request.getParameter(parameterName));
        }

        // 获取嵌入传递的参数
        String APITYPE = request.getParameter("APITYPE");
        if (KHUtil.isNull(APITYPE)) {
            outData = "apiSyncDBData HTTP请求调用错误，任务ID为空：" + APITYPE;
            log.error(outData);
            return JSONObject.toJSONString(new Result(Result.ERROR, outData));
        }

        long dbStartTime = System.currentTimeMillis();

        if (APITYPE == "SyncLGLX_Region") {
            doSyncLGLX_Region(eliteBean, response, APITYPE);
        } else if (APITYPE == "LGLX_Province") {
            doSyncLGLX_Province(eliteBean, response, APITYPE);
        } else if (APITYPE == "LGLX_City") {
            doSyncLGLX_City(eliteBean, response, APITYPE);
        } else if (APITYPE == "LGLX_get_Channel_Type") {
            doSyncLGLX_Channel_Type(eliteBean, response, APITYPE);
        } else if (APITYPE == "LGLX_get_Customer_Category") {
            doSyncLGLX_Customer_Category(eliteBean, response, APITYPE);
        } else if (APITYPE == "ALL") {
            doSyncLGLX_Region(eliteBean, response, "SyncLGLX_Region");
            doSyncLGLX_Province(eliteBean, response, "LGLX_Province");
            doSyncLGLX_City(eliteBean, response, "LGLX_City");
            doSyncLGLX_Channel_Type(eliteBean, response, "LGLX_get_Channel_Type");
            doSyncLGLX_Customer_Category(eliteBean, response, "LGLX_get_Customer_Category");


        }else {
            return JSONObject.toJSONString(new Result(Result.ERROR, "不支持的接口同步类型"));
        }

        return JSONObject.toJSONString(new Result(Result.SUCCESS, "数据同步完成"));
    }

    // 同步乐购乐销大区
    public static JSONObject doSyncLGLX_Region(EliteBean eliteBean, HttpServletResponse response, String APITYPE) {

        try {
            JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

            // 获取任务配置基础数据
            String callURL = KHDBConfig.getAPIURL(eliteBean, APITYPE);
            String callResult = Util.doHttpGet(callURL, "UTF-8", 120000, 0);

            JSONArray callArr = JSONArray.parse(callResult) as JSONArray;
            int callArrNum = callArr.size();
            for (int i = 0; i < callArrNum; i++) {

                String id = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "id");
                String code = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "code");
                String name = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "name");
                String parentId = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "parentId");
                String parentName = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "parentName");
                String parentCode = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "parentCode");
                String organizationId = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "organizationId");
                String organizationCode = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "organizationCode");
                String organizationName = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "organizationName");

                log.debug("查询当前配置数据【JSONObject】：" + callArr.getJSONObject(i).toString());

                String dealSQL = "Select * From Lglx_Market_Area Where Id = ?";
                List<Map<String, Object>> selectCus = jt.queryForList(dealSQL, id);

                log.debug("selectCus：" + selectCus);
                log.debug("检查数据(" + id + ") 数量：" + selectCus.size());

                if (selectCus.size() == 0) {
                    String insertSQL = '''Insert Into Lglx_Market_Area
                                              (Rec_Guid,
                                               Id,
                                               Code,
                                               Name,
                                               Parentid,
                                               Parentname,
                                               Parentcode,
                                               Organizationid,
                                               Organizationcode,
                                               Organizationname,
                                               Status,
                                               Update_By,
                                               Update_Time)
                                            Values
                                              (Uuid(), ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 'SELITE', Now())''';
                    int num = jt.update(insertSQL, id, code, name, parentId, parentName, parentCode, organizationId, organizationCode, organizationName);
                    log.debug("新增数据(" + id + ") 数量：" + num);
                } else {
                    String updateSQL = '''Update Lglx_Market_Area
                                               Set Code             = ?,
                                                   Name             = ?,
                                                   Parentid         = ?,
                                                   Parentname       = ?,
                                                   Parentcode       = ?,
                                                   Organizationid   = ?,
                                                   Organizationcode = ?,
                                                   Organizationname = ?,
                                                   Status           = 1,
                                                   Update_By        = 'SELITE',
                                                   Update_Time      = Now()
                                             Where Id = ?''';
                    int num = jt.update(updateSQL, code, name, parentId, parentName, parentCode, organizationId, organizationCode, organizationName, id);
                    log.debug("更新数据(" + id + ") 数量：" + num);
                }

            }

        } catch (Exception e) {
            log.error("apiSyncAPIData-doSyncLGLX_Region HTTP请求调用错误，接口处理异常：" + e.getMessage(), e);
            return JSONObject.toJSONString(new Result(Result.ERROR, "apiSyncAPIData-doSyncLGLX_Region HTTP请求调用错误，接口处理异常"));

        }

    }

    // 同步乐购乐销-获取全部省份的接⼝
    public static JSONObject doSyncLGLX_Province(EliteBean eliteBean, HttpServletResponse response, String APITYPE) {

        try {
            JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

            // 获取任务配置基础数据
            String callURL = KHDBConfig.getAPIURL(eliteBean, APITYPE);
            String callResult = Util.doHttpGet(callURL, "UTF-8", 120000, 0);

            JSONArray callArr = JSONArray.parse(callResult) as JSONArray;
            int callArrNum = callArr.size();
            for (int i = 0; i < callArrNum; i++) {

                String id = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "id");
                String code = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "code");
                String name = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "name");
                String fullName = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "fullName");
                String countryCode = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "countryCode");
                String countryName = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "countryName");
                String countryId = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "countryId");

                log.debug("查询当前配置数据【JSONObject】：" + callArr.getJSONObject(i).toString());

                String dealSQL = "Select * From lglx_get_province Where Id = ?";
                List<Map<String, Object>> selectCus = jt.queryForList(dealSQL, id);

                log.debug("selectCus：" + selectCus);
                log.debug("检查数据(" + id + ") 数量：" + selectCus.size());

                if (selectCus.size() == 0) {
                    String insertSQL = '''Insert Into Lglx_Get_Province
                                          (Rec_Guid, Id, Code, Name, Fullname, Countrycode, Countryname, Countryid, Sync_Time)
                                        Values
                                          (Uuid(), ?, ?, ?, ?, ?, ?, ?, Now())''';
                    int num = jt.update(insertSQL, id, code, name, fullName, countryCode, countryName, countryId);
                    log.debug("新增数据(" + id + ") 数量：" + num);
                } else {
                    String updateSQL = '''Update Lglx_Get_Province
                                               Set Code        = ?,
                                                   Name        = ?,
                                                   Fullname    = ?,
                                                   Countrycode = ?,
                                                   Countryname = ?,
                                                   Countryid   = ?,
                                                   Sync_Time   = Now()
                                             Where Id = ?''';
                    int num = jt.update(updateSQL, code, name, fullName, countryCode, countryName, countryId, id);
                    log.debug("更新数据(" + id + ") 数量：" + num);
                }

            }

        } catch (Exception e) {
            log.error("apiSyncAPIData-doSyncLGLX_Province HTTP请求调用错误，接口处理异常：" + e.getMessage(), e);
            return JSONObject.toJSONString(new Result(Result.ERROR, "apiSyncAPIData-doSyncLGLX_Province HTTP请求调用错误，接口处理异常"));

        }

    }

    // 同步乐购乐销-获取所有城市的接⼝
    public static JSONObject doSyncLGLX_City(EliteBean eliteBean, HttpServletResponse response, String APITYPE) {

        try {
            JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

            // 获取任务配置基础数据
            String callURL = KHDBConfig.getAPIURL(eliteBean, APITYPE);
            String callResult = Util.doHttpGet(callURL, "UTF-8", 120000, 0);

            JSONArray callArr = JSONArray.parse(callResult) as JSONArray;
            int callArrNum = callArr.size();
            for (int i = 0; i < callArrNum; i++) {

                String id = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "id");
                String code = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "code");
                String name = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "name");
                String countryCode = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "countryCode");
                String countryId = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "countryId");
                String countryName = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "countryName");
                String fullName = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "fullName");
                String provinceId = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "provinceId");
                String provinceCode = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "provinceCode");
                String provinceName = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "provinceName");

                log.debug("查询当前配置数据【JSONObject】：" + callArr.getJSONObject(i).toString());

                String dealSQL = "Select * From lglx_get_ctiy Where Id = ?";
                List<Map<String, Object>> selectCus = jt.queryForList(dealSQL, id);

                log.debug("selectCus：" + selectCus);
                log.debug("检查数据(" + id + ") 数量：" + selectCus.size());

                if (selectCus.size() == 0) {
                    String insertSQL = '''Insert Into Lglx_Get_Ctiy
                                              (Rec_Guid,
                                               Id,
                                               Code,
                                               Name,
                                               Countrycode,
                                               Countryid,
                                               Countryname,
                                               Fullname,
                                               Provinceid,
                                               Provincecode,
                                               Provincename,
                                               Sync_Time)
                                            Values
                                              (Uuid(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, Now())''';
                    int num = jt.update(insertSQL, id, code, name, countryCode, countryId, countryName, fullName, provinceId, provinceCode, provinceName);
                    log.debug("新增数据(" + id + ") 数量：" + num);
                } else {
                    String updateSQL = '''Update Lglx_Get_Ctiy
                                           Set Code         = ?,
                                               Name         = ?,
                                               Countrycode  = ?,
                                               Countryid    = ?,
                                               Countryname  = ?,
                                               Fullname     = ?,
                                               Provinceid   = ?,
                                               Provincecode = ?,
                                               Provincename = ?,
                                               Sync_Time    = Now()
                                         Where Id = ?''';
                    int num = jt.update(updateSQL, code, name, countryCode, countryId, countryName, fullName, provinceId, provinceCode, provinceName, id);
                    log.debug("更新数据(" + id + ") 数量：" + num);
                }

            }

        } catch (Exception e) {
            log.error("apiSyncAPIData-doSyncLGLX_City HTTP请求调用错误，接口处理异常：" + e.getMessage(), e);
            return JSONObject.toJSONString(new Result(Result.ERROR, "apiSyncAPIData-doSyncLGLX_City HTTP请求调用错误，接口处理异常"));

        }

    }

    // 同步乐购乐销-获取渠道类型的接⼝
    public static JSONObject doSyncLGLX_Channel_Type(EliteBean eliteBean, HttpServletResponse response, String APITYPE) {

        try {
            JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

            // 获取任务配置基础数据
            String callURL = KHDBConfig.getAPIURL(eliteBean, APITYPE);
            String callResult = Util.doHttpGet(callURL, "UTF-8", 120000, 0);

            JSONArray callArr = JSONArray.parse(callResult) as JSONArray;
            int callArrNum = callArr.size();
            for (int i = 0; i < callArrNum; i++) {

                String id = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "id");
                String code = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "code");
                String name = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "name");

                log.debug("查询当前配置数据【JSONObject】：" + callArr.getJSONObject(i).toString());

                String dealSQL = "Select * From Lglx_Get_Channel_Type Where Id = ?";
                List<Map<String, Object>> selectCus = jt.queryForList(dealSQL, id);

                log.debug("selectCus：" + selectCus);
                log.debug("检查数据(" + id + ") 数量：" + selectCus.size());

                if (selectCus.size() == 0) {
                    String insertSQL = '''Insert Into Lglx_Get_Channel_Type (Rec_Guid, Id, Code, Name, Sync_Time) Values (Uuid(), ?, ?, ?, Now())''';
                    int num = jt.update(insertSQL, id, code, name);
                    log.debug("新增数据(" + id + ") 数量：" + num);
                } else {
                    String updateSQL = '''Update Lglx_Get_Channel_Type Set Code = ?, Name = ?, Sync_Time = Now() Where Id = ?''';
                    int num = jt.update(updateSQL, code, name, id);
                    log.debug("更新数据(" + id + ") 数量：" + num);
                }

            }

        } catch (Exception e) {
            log.error("apiSyncAPIData-doSyncLGLX_Channel_Type HTTP请求调用错误，接口处理异常：" + e.getMessage(), e);
            return JSONObject.toJSONString(new Result(Result.ERROR, "apiSyncAPIData-doSyncLGLX_Channel_Type HTTP请求调用错误，接口处理异常"));

        }

    }

    // 同步乐购乐销-获取渠道类型的接⼝
    public static JSONObject doSyncLGLX_Customer_Category(EliteBean eliteBean, HttpServletResponse response, String APITYPE) {

        try {
            JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

            // 获取任务配置基础数据
            String callURL = KHDBConfig.getAPIURL(eliteBean, APITYPE);
            String callResult = Util.doHttpGet(callURL, "UTF-8", 120000, 0);

            JSONArray callArr = JSONArray.parse(callResult) as JSONArray;
            int callArrNum = callArr.size();
            for (int i = 0; i < callArrNum; i++) {

                String id = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "id");
                String code = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "code");
                String name = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "name");
                String parentId = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "parentId");
                String parentCode = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "parentCode");
                String parentName = KHUtil.GetSFJV(net.sf.json.JSONObject.fromObject(callArr.getJSONObject(i).toString()), "parentName");

                log.debug("查询当前配置数据【JSONObject】：" + callArr.getJSONObject(i).toString());

                String dealSQL = "Select * From Lglx_Get_Customer_Category Where Id = ?";
                List<Map<String, Object>> selectCus = jt.queryForList(dealSQL, id);

                log.debug("selectCus：" + selectCus);
                log.debug("检查数据(" + id + ") 数量：" + selectCus.size());

                if (selectCus.size() == 0) {
                    String insertSQL = '''Insert Into Lglx_Get_Customer_Category
                                              (Rec_Guid, Id, Code, Name, Parentid, Parentcode, Parentname, Sync_Time)
                                            Values
                                              (Uuid(), ?, ?, ?, ?, ?, ?, Now())''';
                    int num = jt.update(insertSQL, id, code, name, parentId, parentCode, parentName);
                    log.debug("新增数据(" + id + ") 数量：" + num);
                } else {
                    String updateSQL = '''Update Lglx_Get_Customer_Category
                                           Set Code = ?, Name = ?, Parentid = ?, Parentcode = ?, Parentname = ?, Sync_Time = Now()
                                         Where Id = ?''';
                    int num = jt.update(updateSQL, code, name, parentId, parentCode, parentName, id);
                    log.debug("更新数据(" + id + ") 数量：" + num);
                }

            }

        } catch (Exception e) {
            log.error("apiSyncAPIData-doSyncLGLX_Customer_Category HTTP请求调用错误，接口处理异常：" + e.getMessage(), e);
            return JSONObject.toJSONString(new Result(Result.ERROR, "apiSyncAPIData-doSyncLGLX_Customer_Category HTTP请求调用错误，接口处理异常"));

        }

    }

}